package net.huashitong.ssydt.provider.comment.service;

import net.huashitong.comment.vo.*;
import net.huashitong.ssydt.article.entity.SsArticleArticle;
import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.msg.constant.MessageConsts;
import net.huashitong.ssydt.provider.article.service.SsArticleArticleService;
import net.huashitong.ssydt.provider.comment.constant.CommentConsts;
import net.huashitong.ssydt.provider.comment.vo.*;
import net.huashitong.ssydt.provider.constant.SsydtConsts;
import net.huashitong.ssydt.provider.msg.dto.SsSingleMessage;
import net.huashitong.ssydt.provider.msg.service.MsgPushService;
import net.huashitong.ssydt.provider.task.service.SsTaskTaskRecordService;
import net.huashitong.ssydt.provider.utils.StringUtils;
import net.huashitong.ssydt.provider.vo.UserBaseLongIdPagingVO;
import net.huashitong.user.UserManager;
import net.huashitong.user.http.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.09.20
 */
@Service
@Transactional
public class CommentServiceImpl implements CommentService {

    private SdkCommentService sdkCommentService;

    private UserManager userManager;

    private SsArticleArticleService ssArticleArticleService;

    private MsgPushService msgPushService;

    private SsTaskTaskRecordService ssTaskTaskRecordService;

    @Autowired
    public CommentServiceImpl(SdkCommentService sdkCommentService,
                              UserManager userManager,
                              SsArticleArticleService ssArticleArticleService,
                              MsgPushService msgPushService,
                              SsTaskTaskRecordService ssTaskTaskRecordService) {
        this.sdkCommentService = sdkCommentService;
        this.userManager = userManager;
        this.ssArticleArticleService = ssArticleArticleService;
        this.msgPushService = msgPushService;
        this.ssTaskTaskRecordService = ssTaskTaskRecordService;
    }

    @Override
    public List<CommentVO> getArticleTopFiveHotCommonList(Long articleId, String userId) {
        List<HstComment> hstComments = queryArticleTopFiveHotCommonList(articleId, userId);
        List<CommentVO> commentVOS = new ArrayList<>();
        for (HstComment hstComment : hstComments) {
            CommentVO commentVO = getCommentVO(hstComment, userId);
            commentVOS.add(commentVO);
        }
        return commentVOS;
    }

    @Override
    public Integer getArticleNonCheckPass(Long articleId, String userId) {
        NotCheckPassVO commonQueryVO = new NotCheckPassVO();
        commonQueryVO.setUserId(userId);
        commonQueryVO.setProductSource(SsydtConsts.PRODUCT_CODE);
        commonQueryVO.setRelationType(CommentConsts.RelationType.ARTICLE);
        commonQueryVO.setRelationId(String.valueOf(articleId));
        return sdkCommentService.getNonCheckPass(commonQueryVO);
    }

    @Override
    public Integer getArticleCommentsNumber(Long articleId) {
        BaseCommentQueryVO baseCommentQueryVO = new NotCheckPassVO();
        baseCommentQueryVO.setProductSource(SsydtConsts.PRODUCT_CODE);
        baseCommentQueryVO.setRelationType(CommentConsts.RelationType.ARTICLE);
        baseCommentQueryVO.setRelationId(String.valueOf(articleId));
        return sdkCommentService.getCommentsNumber(baseCommentQueryVO);
    }

    @Override
    public MyCommentVO getComments(String userId, Long commentId) {
        HstComment hstComment = sdkCommentService.getComments(commentId);
        if (hstComment == null) {
            throw new ServiceException("评论不存在");
        }
        return getMyCommentVO(hstComment, userId);
    }


    @Override
    public void postReplyComments(ReplyCommentVO replyCommentVO) {
        CommentInVo commentInVo = new CommentInVo();
        BeanUtils.copyProperties(replyCommentVO, commentInVo);
        HstComment hstComment = sdkCommentService.getComments(replyCommentVO.getCommentId());
        if (hstComment == null) {
            throw new ServiceException("该评论已被删除");
        }
        commentInVo.setProductSource(hstComment.getProductSource());
        commentInVo.setRelationType(hstComment.getRelationType());
        commentInVo.setRelationId(hstComment.getRelationId());
        sdkCommentService.postComments(commentInVo);
    }

    @Override
    public void deleteComments(Long commentId, String userId) {
        HstComment hstComment = sdkCommentService.getComments(commentId);
        if (hstComment != null) {
            if (!hstComment.getUserId().equals(userId)) {
                throw new ServiceException("非法操作");
            }
            sdkCommentService.deleteComments(commentId);
        }
    }

    @Override
    public void postCommentPraises(Long commentId, String userId) {
        sdkCommentService.postCommentUsersPraise(commentId, userId);

        //推送提醒
        HstComment hstComment = sdkCommentService.getComments(commentId);
        if (!hstComment.getUserId().equals(userId)) {
            SsSingleMessage ssSingleMessage = new SsSingleMessage();
            ssSingleMessage.setMsgType(MessageConsts.MsgType.COMMENT);
            if (CommentConsts.RelationType.ARTICLE.equals(hstComment.getRelationType())) {
                ssSingleMessage.setTarget(String.valueOf(hstComment.getId()));
                ssSingleMessage.setTargetType(MessageConsts.TargetType.COMMENT);
            }
            ssSingleMessage.setAction(MessageConsts.Action.COMMENT_PRAISES);
            ssSingleMessage.setSender(userId);
            ssSingleMessage.setRecipient(hstComment.getUserId());
            msgPushService.pushSingleMessage(ssSingleMessage);
        }

        //处理任务问题
        ssTaskTaskRecordService.finishTask(userId, 4L);
    }

    @Override
    public List<CommentVO> getCommentList(CommentListQueryVO commentListQueryVO) {
        CommentQueryVO commentQueryVO = new CommentQueryVO();
        BeanUtils.copyProperties(commentListQueryVO, commentQueryVO);
        commentQueryVO.setRelationId(String.valueOf(commentListQueryVO.getRelationId()));
        commentQueryVO.setProductSource(SsydtConsts.PRODUCT_CODE);
        List<HstComment> hstComments = sdkCommentService.getNewestCommonList(commentQueryVO);
        List<CommentVO> commentVOS = new ArrayList<>();
        for (HstComment hstComment : hstComments) {
            CommentVO commentVO = getCommentVO(hstComment, commentListQueryVO.getUserId());
            commentVOS.add(commentVO);
        }
        return commentVOS;
    }

    @Override
    public void postComments(SsydtCommentInVo ssydtCommentInVo) {
        CommentInVo commentInVo = new CommentInVo();
        BeanUtils.copyProperties(ssydtCommentInVo, commentInVo);
        commentInVo.setRelationId(String.valueOf(ssydtCommentInVo.getRelationId()));
        commentInVo.setProductSource(SsydtConsts.PRODUCT_CODE);
        sdkCommentService.postComments(commentInVo);
        //处理任务问题
        ssTaskTaskRecordService.finishTask(ssydtCommentInVo.getUserId(), 5L);
    }

    @Override
    public void deleteCommentPraises(Long commentId, String userId) {
        sdkCommentService.deleteCommentUsersPraise(commentId, userId);
    }

    @Override
    public List<MyCommentVO> getMyCommentList(UserBaseLongIdPagingVO paging) {
        UserCommonQueryVO userCommonQueryVO = new UserCommonQueryVO();
        BeanUtils.copyProperties(paging, userCommonQueryVO);
        List<HstComment> hstComments = sdkCommentService.getUserCommonList(userCommonQueryVO);
        List<MyCommentVO> list = new ArrayList<>();
        for (HstComment hstComment : hstComments) {
            MyCommentVO myCommentVO = getMyCommentVO(hstComment, paging.getUserId());
            list.add(myCommentVO);
        }
        return list;
    }

    private MyCommentVO getMyCommentVO(HstComment hstComment, String userId) {
        CommentVO commentVO = getCommentVO(hstComment, userId);
        MyCommentVO myCommentVO = new MyCommentVO();
        BeanUtils.copyProperties(commentVO, myCommentVO);
        String title;
        switch (hstComment.getRelationType()) {
            case CommentConsts.RelationType.ARTICLE:
                SsArticleArticle article = ssArticleArticleService.selectByPrimaryKey(commentVO.getRelationId());
                title = article.getTitle();
                break;
            default:
                title = "";
                break;
        }
        myCommentVO.setTitle(title);
        return myCommentVO;
    }


    /**
     * 组装CommentVO对象
     *
     * @param hstComment
     * @param userId
     * @return
     */
    private CommentVO getCommentVO(HstComment hstComment, String userId) {
        CommentVO.User user = getUser(hstComment.getUserId());
        CommentVO commentVO = new CommentVO(hstComment, user);
        if (StringUtils.isNotBlank(userId)) {
            Boolean praise = sdkCommentService.getCommentUsersPraise(hstComment.getId(), userId);
            commentVO.setPraise(praise);
        }
        if (hstComment.getCommentId() != null) {
            HstComment hstCommentSource = sdkCommentService.getComments(hstComment.getCommentId());
            CommentVO.QuoteComment quoteComment;
            if (hstCommentSource == null) {
                quoteComment = new CommentVO.QuoteComment();
                user = new CommentVO.User();
                quoteComment.setContent("该评论已被删除");
                quoteComment.setUser(user);
            } else {
                user = getUser(hstCommentSource.getUserId());
                quoteComment = new CommentVO.QuoteComment(hstCommentSource, user);
            }
            commentVO.setQuoteComment(quoteComment);
        }
        return commentVO;
    }

    /**
     * 文章热门评论列表
     *
     * @param articleId
     * @param userId
     * @return
     */
    private List<HstComment> queryArticleTopFiveHotCommonList(Long articleId, String userId) {
        CommentQueryVO commonQueryVO = new CommentQueryVO();
        commonQueryVO.setUserId(userId);
        commonQueryVO.setProductSource(SsydtConsts.PRODUCT_CODE);
        commonQueryVO.setRelationType(CommentConsts.RelationType.ARTICLE);
        commonQueryVO.setRelationId(String.valueOf(articleId));
        commonQueryVO.setPageSize(5);
        return sdkCommentService.getHotCommonList(commonQueryVO);
    }

    /**
     * @param userId
     * @return
     */
    private CommentVO.User getUser(String userId) {
        CommentVO.User userVO = new CommentVO.User();
        Result<net.huashitong.user.results.User> rs = userManager.get(userId);
        if (rs.getCode().equals(Result.Status.SUCCESS)) {
            net.huashitong.user.results.User user = rs.getResults();
            userVO.setImageUrl(user.getImageUrl());
            userVO.setNickname(user.getNickname());
            userVO.setUserId(user.getUserId());
        } else {
            throw new ServiceException("用户不存在");
        }
        return userVO;
    }
}
